package torchtools.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * @author Matt
 */
public class IOUtil {

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
    
        // The directory is now empty so delete it
        return dir.delete();
    }
    
    /** Copies file source to file target. */
    public static void copy(File source, File target) throws IOException {
        InputStream in = new FileInputStream(source);
        OutputStream out = new FileOutputStream(target);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
    
    public static void copyToDir(File source, File target, boolean overwrite) throws IOException {
        String name = source.getName();
        File targetFile = new File(target.getPath()+"\\"+name);
        if (!targetFile.exists() || overwrite)
            copy(source, targetFile);
    }
    
    /** Copies an entire directory to the given file location. */
    public static void copyDir(File sourceLocation, File targetLocation)
            throws IOException {
        copyDir(sourceLocation, targetLocation, null);
    }
    
    public static void copyDir(File sourceLocation, File targetLocation, 
            FilenameFilter filter) throws IOException {
        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

            String[] children = sourceLocation.list(filter);
            for (int i = 0; i < children.length; i++) {
                copyDir(new File(sourceLocation, children[i]),
                        new File(targetLocation, children[i]), filter);
            }
        } else {
            copy(sourceLocation, targetLocation);
        }
    }
}
